package ${names.controllerPackage};

import ${names.domainPackage}.${names.domainClassName};
import ${names.servicePackage}.${names.serviceClassName};
import com.mirror.tk.web.common.Constant;
import com.mirror.tk.core.log.annotation.Log;
import com.mirror.tk.web.controller.CommonController;
import com.mirror.tk.framework.common.web.support.JsonResult;
import com.mirror.tk.framework.common.web.support.JsonListResult;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.ui.ModelMap;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import java.util.*;


@Controller
@RequestMapping(value = "${configuration.pageMapping}")
public class ${names.controllerClassName} extends CommonController {

    @Resource
    private ${names.serviceClassName} ${names.serviceClassName?uncap_first};
    
    // 列表
    private static final String ${configuration.pagePrefix?upper_case}_LIST = "${configuration.pageMapping?substring(1)}/${configuration.pagePrefix}_list";
    // 详情
    private static final String ${configuration.pagePrefix?upper_case}_VIEW = "${configuration.pageMapping?substring(1)}/${configuration.pagePrefix}_view";
    // 新增/修改
    private static final String ${configuration.pagePrefix?upper_case}_DETAIL = "${configuration.pageMapping?substring(1)}/${configuration.pagePrefix}_detail";

    // 列表-查看
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(HttpServletRequest request, ModelMap map) {

    <#list table.columnMetadatas as entity>
    <#if configuration.searchColumnsList?size==0 || configuration.searchColumnsList?seq_contains(entity.name?lower_case)>
	    <#if entity.javaDataType?lower_case=='date'>
	    //${entity.common} 默认时间范围3个月
	    map.put("end${entity.propertyName?cap_first}", Calendar.getInstance().getTime());
	    map.put("begin${entity.propertyName?cap_first}", DateUtils.addMonths(Calendar.getInstance().getTime(), -3));
	    </#if>
    </#if>
    </#list>

        return ${configuration.pagePrefix?upper_case}_LIST;
    }
    
    // 列表-数据
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public JsonListResult<${names.domainClassName}> ajaxList(HttpServletRequest request,
    <#assign counter=0 />
    <#list table.columnMetadatas as entity>
        <#if configuration.searchColumnsList?size==0 || configuration.searchColumnsList?seq_contains(entity.name?lower_case)>
        <#assign counter=counter+1 />
            <#if entity.dataType == 2>
            @RequestParam(value="begin${entity.propertyName?cap_first}", required=false) ${entity.javaDataType} begin${entity.propertyName?cap_first},
            @RequestParam(value="end${entity.propertyName?cap_first}", required=false) ${entity.javaDataType} end${entity.propertyName?cap_first}<#if entity_has_next && (configuration.searchColumnsList?size==0 || configuration.searchColumnsList?size>counter)>,</#if>
            <#else>
            @RequestParam(value="${entity.propertyName}", required=false) ${entity.javaDataType} ${entity.propertyName}<#if entity_has_next && (configuration.searchColumnsList?size==0 || configuration.searchColumnsList?size>counter)>,</#if>
            </#if>
        </#if>
    </#list>
            ) {

<#list table.columnMetadatas as entity>
    <#if configuration.searchColumnsList?size==0 || configuration.searchColumnsList?seq_contains(entity.name?lower_case)>
    <#if entity.javaDataType?lower_case=='date'>
        //${entity.common} 默认时间范围3个月
        if(end${entity.propertyName?cap_first}==null){
            end${entity.propertyName?cap_first}=Calendar.getInstance().getTime();
        }
        if(begin${entity.propertyName?cap_first}==null){
            begin${entity.propertyName?cap_first} = DateUtils.addMonths(end${entity.propertyName?cap_first}, -3);
        }
    </#if>
    </#if>
</#list>

        Map<String, Object> searchMap = new HashMap<String, Object>();
        Map<String, Boolean> sortMap = new HashMap<String, Boolean>();

<#--查询条件-->
<#list table.columnMetadatas as entity>
    <#if configuration.searchColumnsList?size==0 || configuration.searchColumnsList?seq_contains(entity.name?lower_case)>
        //${entity.common}
        <#if entity.javaDataType?lower_case=='string'>
        if(StringUtils.isNotBlank(${entity.propertyName})){
            searchMap.put("LIKE_${entity.propertyName}", ${entity.propertyName});
        }
        <#elseif entity.javaDataType?lower_case=='date'>
        if(begin${entity.propertyName?cap_first}!=null){
            searchMap.put("GTE_${entity.propertyName}", DateUtils.truncate(begin${entity.propertyName?cap_first}, Calendar.DATE));
        }
        if(end${entity.propertyName?cap_first}!=null){
            searchMap.put("LTE_${entity.propertyName}", DateUtils.truncate(DateUtils.addDays(end${entity.propertyName?cap_first}, 1), Calendar.DATE));
        }
        <#else>
        if(${entity.propertyName}!=null){
            searchMap.put("EQ_${entity.propertyName}", ${entity.propertyName});
        }
        </#if>
    </#if>
</#list>
        return toJsonListResult(${names.serviceClassName?uncap_first}.query(fromJsonListResult(request), searchMap, sortMap));
    }

    // 新增-查看
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(HttpServletRequest request, ModelMap map){
        return ${configuration.pagePrefix?upper_case}_DETAIL;
    }

    // 新增-保存
    @ResponseBody
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @Log(module = "${names.domainClassName}", moduleName = "${table.comment}", action = "ajaxAdd", actionName = "${table.comment}新增")
    public JsonResult ajaxAdd(HttpServletRequest request, ${names.domainClassName} ${names.domainClassName?uncap_first}){
        JsonResult result = new JsonResult(false);
        try{
        <#list table.columnMetadatas as entity>
            <#if entity.propertyName=='id'>
            //${entity.common}
            ${names.domainClassName?uncap_first}.set${entity.propertyName?cap_first}(null);
            <#elseif entity.name?lower_case != 'id' && configuration.detailColumnsList?size gte 1 && false == configuration.detailColumnsList?seq_contains(entity.name?lower_case)>
            //${entity.common}
            ${names.domainClassName?uncap_first}.set${entity.propertyName?cap_first}(null);
            </#if>
        </#list>

            ${names.serviceClassName?uncap_first}.save(${names.domainClassName?uncap_first});
        }catch (Exception ex){
            logger.error("Save Method (inster) ${names.domainClassName} Error : {}", ex.getMessage());
            result.setMessage(Constant.I18nMessage.SAVE_FAILURE);
            result.setCode(Constant.Application.FAILURE);
            return result;
        }
        result.setMessage(Constant.I18nMessage.SAVE_SUCCESS);
        result.setCode(Constant.Application.SUCCESS);
        result.setSuccess(true);
        return result;
    }

    // 编辑-查看
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String update(HttpServletRequest request, ModelMap map, @RequestParam(value = "id") Long id){
        ${names.domainClassName} ${names.domainClassName?uncap_first} = ${names.serviceClassName?uncap_first}.get(id);
        if(${names.domainClassName?uncap_first}==null){
            //没有记录
            return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.RECORD_NOT_FOUND), map);
        }
        map.put("item", ${names.domainClassName?uncap_first});
        return ${configuration.pagePrefix?upper_case}_DETAIL;
    }

    // 编辑-保存
    @ResponseBody
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @Log(module = "${names.domainClassName}", moduleName = "${table.comment}", action = "ajaxUpdate", actionName = "${table.comment}编辑")
    public JsonResult ajaxUpdate(HttpServletRequest request, ${names.domainClassName} ${names.domainClassName?uncap_first}){
        JsonResult result = new JsonResult(false);
        if(${names.domainClassName?uncap_first}==null || ${names.domainClassName?uncap_first}.getId()==null){
            //没有记录
            result.setMessage(Constant.I18nMessage.RECORD_NOT_FOUND);
            result.setCode(Constant.Application.FAILURE);
            return result;
        }
        try{
            ${names.domainClassName} source${names.domainClassName} = ${names.serviceClassName?uncap_first}.get(${names.domainClassName?uncap_first}.getId());
            if(source${names.domainClassName}==null){
                //没有记录
                result.setMessage(Constant.I18nMessage.RECORD_NOT_FOUND);
                result.setCode(Constant.Application.FAILURE);
                return result;
            }

        <#list table.columnMetadatas as entity>
        <#if entity.name?lower_case != 'id' && (configuration.detailColumnsList?size==0 || configuration.detailColumnsList?seq_contains(entity.name?lower_case))>
            //${entity.common}
            source${names.domainClassName}.set${entity.propertyName?cap_first}(${names.domainClassName?uncap_first}.get${entity.propertyName?cap_first}());
        </#if>
        </#list>
            ${names.serviceClassName?uncap_first}.update(source${names.domainClassName});
            ${names.domainClassName?uncap_first} = source${names.domainClassName};
        }catch (Exception ex){
            logger.error("Save Method (Update) ${names.domainClassName} Error : {}", ex.getMessage());
            result.setMessage(Constant.I18nMessage.UPDATE_FAILURE);
            result.setCode(Constant.Application.FAILURE);
            return result;
        }
        result.setMessage(Constant.I18nMessage.UPDATE_SUCCESS);
        result.setCode(Constant.Application.SUCCESS);
        result.setSuccess(true);
        return result;
    }

    // 详情
    @RequestMapping(value = "view", method = RequestMethod.GET)
    public String show(HttpServletRequest request, ModelMap map, @RequestParam(value = "id") Long id){
        ${names.domainClassName} ${names.domainClassName?uncap_first} = ${names.serviceClassName?uncap_first}.get(id);
        if(${names.domainClassName?uncap_first}==null){
            //没有记录
            return super.operFailure(new RequestContext(request).getMessage(Constant.I18nMessage.RECORD_NOT_FOUND), map);
        }
        map.put("item", ${names.domainClassName?uncap_first});
        return ${configuration.pagePrefix?upper_case}_VIEW;
    }

    // 删除
    @ResponseBody
    @RequestMapping(value = "del", method = RequestMethod.POST)
    @Log(module = "${names.domainClassName}", moduleName = "${table.comment}", action = "ajaxDel", actionName = "${table.comment}删除")
    public JsonResult ajaxDel(HttpServletRequest request, @RequestParam(value = "id") Long id){
        JsonResult result = new JsonResult(false);
        try{
            ${names.serviceClassName?uncap_first}.removeById(id);
        }catch (Exception ex){
            logger.error("Del Method (Del) ${names.domainClassName} Error : {}", ex.getMessage());
            //删除失败
            result.setMessage(Constant.I18nMessage.DEL_FAILURE);
            result.setCode(Constant.Application.FAILURE);
            return result;
        }
        result.setMessage(Constant.I18nMessage.DEL_SUCCESS);
        result.setCode(Constant.Application.SUCCESS);
        result.setSuccess(true);
        return result;
    }

}
